<template>
  <view>
    <view class="tab-box">
      <u-tabs-swiper
        ref="uTabs"
        :list="tabsList"
        :current="current"
        :is-scroll="false"
        swiperWidth="750"
      ></u-tabs-swiper>
    </view>
    <view class="center-content">
      <view v-for="(item, index) in tabsList" :key="index">
        <DynamicFormRender
          v-if="item.isForm && current === index"
          ref="reviewFormRef"
          :form-id="tabsList[index].id"
          :form-business-level="4"
          :query-value-flag="1"
          :projectId="projectId"
        />
        <fileListCom
          v-else-if="tabsList[current].name === '上传文件' && current === index"
          ref="refDynamicTable"
          :taskInfo="{ taskId, taskType }"
          :isUpload="true"
        ></fileListCom>
      </view>
    </view>
    <view class="btn-box u-flex u-row-between fileList-sign-btn">
      <u-button shape="circle" v-if="current !== 0" @click="prev()"
        >上一步</u-button
      >
      <u-button
        shape="circle"
        type="primary"
        :loading="loading"
        plain
        @click="next(false)"
        >暂存</u-button
      >
      <u-button
        v-if="!showSubmitBtn()"
        :loading="loading"
        shape="circle"
        type="primary"
        @click="next(true)"
        >下一步</u-button
      >
      <u-button
        v-if="showSubmitBtn()"
        :loading="loading"
        shape="circle"
        type="primary"
        @click="next(true)"
        >提交</u-button
      >

      <!-- <a-button type="primary" ghost :loading="loading" @click="next(false)">暂存</a-button> -->
      <!-- <a-button v-if="current !== 0" type="primary" @click="prev()">上一步</a-button>
          <a-button v-if="!showSubmitBtn()" type="primary" :loading="loading" @click="next(true)">下一步</a-button>
          <a-button v-if="showSubmitBtn()" type="primary" :loading="loading" @click="next(true)">提交</a-button> -->
    </view>
  </view>
  <initiatorSetApptoval
    ref="refInitiatorSetApptoval"
    @submit="handleOk"
  ></initiatorSetApptoval>
</template>
<script lang="ts" setup>
import { formListApp, taskFormSubmit } from '@/api/modules/form';
import { taskFeedback } from '@/api/modules/project';
import { getFlowDynamicApprovals, getTaskFlow } from '@/api/modules/flow';
import { onLoad } from '@dcloudio/uni-app';
import DynamicFormRender from '@/components/DynamicFormRender/index.vue';
import { getTaskFileDetailList } from '@/api/modules/fileList';
import fileListCom from '@/components/fileList/index.vue';
import { cellClick } from '@/hooks/useBack';
import initiatorSetApptoval from '@/pages/approval/initiatorSetApptoval.vue';

const tabsList = ref<any[]>([]);
const current = ref(0);
const reviewFormRef = ref();
const refDynamicTable = ref();
const refInitiatorSetApptoval = ref();

const formList = ref<any[]>([]);
const getFormList = async () => {
  const res: any = await formListApp({ belongBusinessId: taskId.value });
  if (res) {
    formList.value = res;
    tabsList.value = res.map((item: any) => ({
      name: item.formName,
      isForm: true,
      id: item.formId,
    }));
    if (needFile.value) {
      tabsList.value.push({
        name: '上传文件',
        id: taskId.value,
      });
    }
  }
};
const showSubmitBtn = () => {
  let flag = false;
  if (needFile.value) {
    if (current.value === formList.value.length) {
      flag = true;
    }
  } else if (current.value === formList.value.length - 1) {
    flag = true;
  }
  return flag;
};
// 获取提交的数据
async function getSubmitData(submit: any) {
  const params: any = {
    taskId: taskId.value,
    submit: submit,
    approvalNodeInfoList: approvalNodeInfoList.value,
  };
  if (current.value <= formList.value.length - 1) {
    // 提交表单
    params.form = {};
    const res = await reviewFormRef.value[current.value].getData(submit);
    console.log(res);
    params.form.formId = tabsList.value[current.value].id;
    params.form.fieldList = res;
  } else {
    if (!fileList.value || fileList.value.length === 0) {
      return params;
    }
    // 提交文件
    if (submit) {
      try {
        refDynamicTable.value[0].check();
      } catch (e: any) {
        uni.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000,
        });
        return false;
      }
    }
    params.fileList = refDynamicTable.value[0].getData();
  }
  return params;
}
async function submit(params: any) {
  loading.value = true;
  taskFeedback(params)
    .then(() => {
      uni.showToast({
        title: params.submit ? '任务反馈成功' : '任务暂存成功',
        icon: 'none',
        duration: 2000,
      });
      // proxy.mittBus.emit(mittEvent.HIDE_TASK_MODAL, taskInfo.taskId);
      cellClick();
    })
    .finally(() => {
      loading.value = false;
    });
}
// 提交后查询是否需要设置下一个审批人
const approvalNodeInfoList = ref<any[]>([]);
const needApproval = ref<any>([]);
function setFlowApprovals(params: any) {
  getFlowDynamicApprovals({ taskId: taskId.value }).then(async (res: any) => {
    console.log(res);
    if (res.length) {
      // 需要设置审批人
      const nodeIds = res.map((item: any) => item.nodeId);
      needApproval.value = nodeIds;
      refInitiatorSetApptoval.value.show(res);
    } else {
      // 不需要就直接提交
      submit(params);
    }
  });
}
// 选择审批节点后提交
const handleOk = async (data: any) => {
  console.log(data);
  approvalNodeInfoList.value = data.map((item: any) => ({
    ...item,
    dynamicParam: item.dynamicParam === 0 ? 'PRE' : 'ROLE',
  }));
  const params = await getSubmitData(true);
  submit(params);
};
/**
 * submit: 提交或暂存； isLast 是否到了最后一步
 */
const loading = ref(false);
const next = async (isSubmit: boolean) => {
  // showSubmitBtn.value 为true时是最后一步
  if (showSubmitBtn()) {
    // 最后一步提交
    // 第一步：取参数
    const params = await getSubmitData(isSubmit);
    if (!params) {
      return;
    }
    // 第二步：如果是暂存，走submit, 结束掉
    if (!isSubmit) {
      submit(params);
      return;
    }
    // 第三步：正式提交，查询是否需要设置下一步审批人, 后续submit会在setFlowApprovals方法中执行，结束
    setFlowApprovals(params);
  } else {
    // 如果不是最后一步，肯定是提交表单，毋庸置疑
    const params = await getSubmitData(isSubmit);
    loading.value = true;
    taskFormSubmit(params)
      .then(() => {
        if (isSubmit) {
          if (current.value + 1 < tabsList.value.length) {
            current.value++;
          }
        } else {
          uni.showToast({
            title: isSubmit ? '任务保存成功' : '任务暂存成功',
            icon: 'none',
            duration: 2000,
          });
          cellClick();
          // message.success(isSubmit ? '任务保存成功' : '任务暂存成功');
          // proxy.mittBus.emit(mittEvent.HIDE_TASK_MODAL, taskId.value);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  }
};

// const next = () => {
//   if (current.value + 1 < tabsList.value.length) {
//     current.value++;
//   }
// };
const prev = () => {
  if (current.value - 1 >= 0) {
    current.value--;
  }
};

const fileList = ref<any>([]);
const getFileList = async () => {
  const res: any = await getTaskFileDetailList({ taskId: taskId.value });
  if (res) {
    fileList.value = res.map((item: any) => {
      item.fileDetailList = item.fileDetailList || [];
      return item;
    });
  }
};

const taskId = ref<any>({});
const taskType = ref();
const needFile = ref<boolean>(false);
const projectId = ref<string>('');
onLoad(() => {
  const {
    taskId: tId,
    needFile: nFile,
    projectId: pId,
    taskType: tType,
  } = (uni as any).$Router.getQuery();
  taskId.value = tId;
  needFile.value = nFile;
  projectId.value = pId;
  taskType.value = tType;
  getFormList();
  getFileList();
});
</script>
<style lang="scss">
.tab-box {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 10;
}
.center-content {
  padding: 0 20rpx;
  padding-top: 80rpx;
  padding-bottom: 188rpx;
}
.btn-box {
  bottom: 0;
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
  position: fixed;
  z-index: 10;
}
</style>
